import json
import threading
from datetime import datetime
from credit_voice_service.dialogue.util.rabbitMQ_sender import RabbitMQSender
from credit_voice_service.settings import MQ_CONFIG, log
from dialogue.service.dialogue_storage import dialogueStorage


class RabbitMQService:
    def __init__(self):
        self.sender = RabbitMQSender(username=MQ_CONFIG.get("username"), password=MQ_CONFIG.get("password"),
                                     host=MQ_CONFIG.get("hostname"), port=MQ_CONFIG.get("port"),
                                     vhost=MQ_CONFIG.get("vhost"), queue_name=MQ_CONFIG.get("queue"))

    def publish(self, session_id, message):
        try:
            self.sender.connect()
            self.sender.publish("dm_record", "dm_record", message)
        except Exception as e:
            log.error("[publish] send MQ error:{} data:{}".format(e, message))
            dialogueStorage.mq_error_data(msg=message)
        finally:
            self.sender.close()


def send_message(session_id, message):
    rabbitMq_ser = RabbitMQService()
    rabbitMqThread = threading.Thread(target=rabbitMq_ser.publish(session_id, message))
    rabbitMqThread.start()
    # rabbitMqThread.join()
    print("Thread execution finished.")


if __name__ == '__main__':
    message = {
        "msgContent": "测试数据6",
        "workspaceId": 55369,
        "speakerType": "IVR",
        "sessionId": "0-2120-671322255-1667158375230459904-490",
        "msgTime": datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")[:-3]
    }
    send_message("0-2120-671322255-1667158375230459904-490", json.dumps(message))
    pass
